import type { Tab } from '@/index.d';
import { defineStore } from 'pinia';
import type { RouteLocationNormalizedLoaded } from 'vue-router';

export const useTabsViewStore = defineStore(
  'useTabsViewStore',
  () => {
    const tabList = ref<Tab[]>([
      {
        path: '/home',
        title: '首页',
        name: 'Home'
      }
    ]);

    const routeNameList = computed<string[]>(() => tabList.value.map(itme => itme.name));

    const getTabList = () => tabList;

    const maxTabs = ref<number>(10);

    const removeByPath = async (path: string) => {
      tabList.value = tabList.value.filter(item => item.path !== path);
    };

    const removeByName = async (name: string) => {
      tabList.value = tabList.value.filter(item => item.name !== name);
    };

    const isIncludePath = (path: string): boolean => tabList.value.some(item => item.path === path);

    const isIncludeName = (name: string): boolean => tabList.value.some(item => item.name === name);

    const addTab = (route: RouteLocationNormalizedLoaded) => {
      const { path, meta, name } = route;
      if (tabList.value.some(item => item.path === path)) {
        return;
      }
      tabList.value.length >= maxTabs.value && tabList.value.splice(1, 1);
      const tab = {
        title: meta.title as string,
        path,
        name: name as string
      };
      tabList.value.push(tab);
    };

    return {
      tabList,
      getTabList,
      routeNameList,
      removeByName,
      maxTabs,
      removeByPath,
      isIncludeName,
      isIncludePath,
      addTab
    };
  },
  { persist: true }
);
